"""
创建测试反馈数据脚本
用于演示问题解决率趋势功能
"""
import os
import django
import sys

# 设置Django环境
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SERVER_SETTINGS_MODULE', 'deepseek_project.settings')
django.setup()

from deepseek_api.models import User, ConversationSession
from django.utils import timezone
from datetime import timedelta
import random

def create_test_feedback_data():
    """创建测试反馈数据"""
    
    # 获取或创建测试用户
    users = list(User.objects.all())
    if not users:
        print("❌ 没有找到用户，请先创建用户")
        return
    
    print(f"✅ 找到 {len(users)} 个用户")
    
    # 删除旧的测试会话（可选）
    # ConversationSession.objects.filter(session_id__startswith='test_feedback_').delete()
    
    # 为最近7天创建测试数据
    created_count = 0
    for day_offset in range(7):
        date = timezone.now() - timedelta(days=6-day_offset)
        
        # 每天创建5-15个会话
        sessions_count = random.randint(5, 15)
        
        for i in range(sessions_count):
            user = random.choice(users)
            session_id = f"test_feedback_{date.strftime('%Y%m%d')}_{i}"
            
            # 随机生成问题类型
            problem_types = [
                ("网络连接失败", "AI: 请检查网络配置..."),
                ("系统报错", "AI: 这个错误通常是由于..."),
                ("性能很慢", "AI: 建议优化数据库查询..."),
                ("配置不正确", "AI: 请修改配置文件..."),
                ("无法启动服务", "AI: 检查端口是否被占用...")
            ]
            
            problem, solution = random.choice(problem_types)
            context = f"用户：{problem}\n回复：{solution}\n"
            
            # 创建或更新会话
            session, created = ConversationSession.objects.update_or_create(
                session_id=session_id,
                user=user,
                defaults={
                    'context': context,
                    'created_at': date,
                    'updated_at': date,
                }
            )
            
            # 设置反馈状态
            # 模拟真实情况：70-90%的问题被解决
            resolution_rate = random.uniform(0.7, 0.9)
            is_resolved = random.random() < resolution_rate
            
            session.is_resolved = is_resolved
            session.feedback_time = date + timedelta(minutes=random.randint(1, 30))
            session.save()
            
            if created:
                created_count += 1
    
    print(f"✅ 成功创建 {created_count} 个测试会话")
    
    # 统计每天的解决率
    print("\n📊 每日问题解决率统计：")
    for day_offset in range(7):
        date = (timezone.now() - timedelta(days=6-day_offset)).date()
        
        total = ConversationSession.objects.filter(created_at__date=date).count()
        resolved = ConversationSession.objects.filter(
            created_at__date=date,
            is_resolved=True
        ).count()
        
        if total > 0:
            rate = (resolved / total) * 100
            print(f"  {date.strftime('%m-%d')}: {rate:.1f}% ({resolved}/{total} 已解决)")
        else:
            print(f"  {date.strftime('%m-%d')}: 无数据")

if __name__ == '__main__':
    print("🚀 开始创建测试反馈数据...\n")
    create_test_feedback_data()
    print("\n✅ 完成！现在可以查看管理端的问题解决率趋势图了！")

